<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="作者ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入作者ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="作者" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入作者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作品标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入作品标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
     <!-- <el-form-item label="浏览量" prop="viewCount">
        <el-input
          v-model="queryParams.viewCount"
          placeholder="请输入浏览量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

   <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['foodworks:works:works:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['foodworks:works:works:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['foodworks:works:works:remove']"
        >删除</el-button>
      </el-col>
     <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['foodworks:works:works:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleBatchAudit"
          v-hasPermi="['foodworks:works:works:audit']"
        >批量审核</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="worksList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="作品ID" align="center" prop="workId" />
      <el-table-column label="作者ID" align="center" prop="userId" />
      <el-table-column label="作者" align="center" prop="nickname" />
      <el-table-column label="作品标题" align="center" prop="title" />
      <el-table-column label="作品详情" align="center" prop="content">
        <template slot-scope="scope">
          <div style="max-width: 300px; max-height: 100px; overflow: hidden; text-overflow: ellipsis; line-height: 1.4;">{{ stripHtml(scope.row.content) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="封面图" align="center" prop="coverImg" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.coverImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
    <!-- <el-table-column label="浏览量" align="center" prop="viewCount" /> -->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="warning">待审核</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success">已通过</el-tag>
          <el-tag v-else type="info">未知状态</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <!-- 新增审核功能 -->
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleAudit(scope.row)"
            v-hasPermi="['foodworks:works:works:audit']"
            v-if="scope.row.status === 0"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['foodworks:works:works:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改作品详情对话框 -->
    <!-- <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="作者ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入作者ID" />
        </el-form-item>
        <el-form-item label="作品标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入作品标题" />
        </el-form-item>
        <el-form-item label="作品详情">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="封面图" prop="coverImg">
          <image-upload v-model="form.coverImg"/>
        </el-form-item>
        <el-form-item label="浏览量" prop="viewCount">
          <el-input v-model="form.viewCount" placeholder="请输入浏览量" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.pass_no_yes"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否删除：0正常 1删除" prop="del">
          <el-input v-model="form.del" placeholder="请输入是否删除：0正常 1删除" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog> -->

    <!-- 审核作品对话框 -->
    <el-dialog :title="'审核作品 - ' + auditForm.title" :visible.sync="auditOpen" width="600px" append-to-body>
      <el-form ref="auditForm" :model="auditForm" label-width="80px">
        <el-form-item label="作者">
          <span>{{ auditForm.nickname }}</span>
        </el-form-item>
        <el-form-item label="作品标题">
          <span>{{ auditForm.title }}</span>
        </el-form-item>
        <el-form-item label="作品详情">
          <div v-html="auditForm.content" style="max-height: 200px; overflow-y: auto; border: 1px solid #dcdfe6; padding: 10px; border-radius: 4px;"></div>
        </el-form-item>
        <el-form-item label="封面图">
          <image-preview :src="auditForm.coverImg" :width="100" :height="100"/>
        </el-form-item>
        <el-form-item label="发布时间">
          <span>{{ parseTime(auditForm.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </el-form-item>
        <el-form-item label="审核结果" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input
            v-model="auditForm.auditRemark"
            type="textarea"
            :rows="3"
            placeholder="请输入审核备注（可选）"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAudit">确 定</el-button>
        <el-button @click="cancelAudit">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWorks, getWorks, delWorks, addWorks, updateWorks, auditWorks, batchAuditWorks } from "@/api/foodworks/works/works"

export default {
  name: "Works",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 作品详情表格数据
      worksList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        nickname: null,
        title: null,
        content: null,
        viewCount: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "作者ID不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "作品标题不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "发布时间不能为空", trigger: "blur" }
        ],
        viewCount: [
          { required: true, message: "浏览量不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        del: [
          { required: true, message: "是否删除：0正常 1删除不能为空", trigger: "blur" }
        ]
      },
      // 审核相关
      auditOpen: false,
      auditForm: {
        workId: null,
        userId: null,
        nickname: null,
        title: null,
        content: null,
        coverImg: null,
        createTime: null,
        auditStatus: null,
        auditRemark: null
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询作品详情列表 */
    getList() {
      this.loading = true
      listWorks(this.queryParams).then(response => {
        this.worksList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        workId: null,
        userId: null,
        title: null,
        content: null,
        coverImg: null,
        createTime: null,
        viewCount: null,
        status: null,
        del: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.workId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    // handleAdd() {
    //   this.reset()
    //   this.open = true
    //   this.title = "添加作品详情"
    // },
    /** 修改按钮操作 */
    // handleUpdate(row) {
    //   this.reset()
    //   const workId = row.workId || this.ids
    //   getWorks(workId).then(response => {
    //     this.form = response.data
    //     this.open = true
    //     this.title = "修改作品详情"
    //   })
    // },
    /** 提交按钮 */
    // submitForm() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       if (this.form.workId != null) {
    //         updateWorks(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功")
    //           this.open = false
    //           this.getList()
    //         })
    //       } else {
    //         addWorks(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功")
    //           this.open = false
    //           this.getList()
    //         })
    //       }
    //     }
    //   })
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const workIds = row.workId || this.ids
      this.$modal.confirm('是否确认删除作品详情编号为"' + workIds + '"的数据项？').then(function() {
        return delWorks(workIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download('foodworks/works/works/export', {
    //     ...this.queryParams
    //   }, `works_${new Date().getTime()}.xlsx`)
    // }

    /** 审核按钮操作 */
    handleAudit(row) {
      this.auditForm = {
        workId: row.workId,
        userId: row.userId,
        nickname: row.nickname,
        title: row.title,
        content: row.content,
        coverImg: row.coverImg,
        createTime: row.createTime,
        auditStatus: null,
        auditRemark: null
      }
      this.auditOpen = true
    },
    /** 提交审核 */
    submitAudit() {
      this.$refs["auditForm"].validate(valid => {
        if (valid) {
          const auditData = {
            workId: this.auditForm.workId,
            status: this.auditForm.auditStatus,
            remark: this.auditForm.auditRemark
          }
          auditWorks(auditData).then(response => {
            this.$modal.msgSuccess("审核成功")
            this.auditOpen = false
            this.getList()
          }).catch(error => {
            this.$modal.msgError(error.msg)
          })
        }
      })
    },
    /** 取消审核 */
    cancelAudit() {
      this.auditOpen = false
      this.resetAuditForm()
    },
    /** 重置审核表单 */
    resetAuditForm() {
      this.auditForm = {
        workId: null,
        userId: null,
        nickname: null,
        title: null,
        content: null,
        coverImg: null,
        createTime: null,
        auditStatus: null,
        auditRemark: null
      }
      this.resetForm("auditForm")
    },
    /** 批量审核操作 */
    handleBatchAudit() {
      this.$modal.prompt('请输入审核备注（可选）', '批量审核', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入审核备注'
      }).then(({ value }) => {
        const auditData = {
          workIds: this.ids,
          status: 1, // 默认通过
          remark: value || ''
        }
        return batchAuditWorks(auditData)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("批量审核成功")
      }).catch(() => {})
    },
    /** 去除HTML标签，只显示纯文本 */
    stripHtml(html) {
      if (!html) return ''
      const tmp = document.createElement('div')
      tmp.innerHTML = html
      return tmp.textContent || tmp.innerText || ''
    }
  }
}
</script>
